package com.wudao.ncmplay.controller;

import com.wudao.ncmplay.config.NcmProperties;
import com.wudao.ncmplay.resolver.I18nMessageUtil;
import com.wudao.ncmplay.service.NcmService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.TagException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @desc ncm控制类
 * @author minddle2boy
 */
@RequestMapping("/ncm")
@RestController
public class NcmController
{
    private static final Logger LOGGER = LogManager.getLogger(NcmController.class);

    @Resource
    private NcmProperties ncmProperties;

    @Resource
    private NcmService ncmService;

    @Resource
    private I18nMessageUtil i18nMessage;

    /**
     * 更改ncm文件
     */
    @GetMapping("/change")
    @ResponseBody
    public String changeNcm()
    {
        String filePath = ncmProperties.getFilePath();
        File file = new File(filePath);
        if(!file.exists()){
            LOGGER.error("文件夹不存在");
            return i18nMessage.getMessage("error.file.not.exists");
        }
        FileFilter filter = pathname -> pathname.getName().endsWith(".ncm");
        List<File> fileList = iterator(file, filter);
        StringBuilder fileName = new StringBuilder();
        fileList.forEach(obj->{
            try {
                String targetFile = ncmService.ncm2NormalFormat(obj);
                fileName.append(";").append(targetFile);
            } catch (TagException | ReadOnlyFileException | CannotReadException | InvalidAudioFrameException | IOException | CannotWriteException e) {
                e.printStackTrace();
            }
        });
        return fileName.toString().replaceFirst(";","");
    }

    /**
     * 更改ncm文件
     */
    @GetMapping("/change/path")
    @ResponseBody
    public String changeNcmByPath(@RequestParam(required = false) String path)
    {
        File file = new File(path);
        if(!file.exists()){
            LOGGER.error("文件夹不存在");
            return "文件夹不存在";
        }
        FileFilter filter = pathname -> pathname.getName().endsWith(".ncm");
        List<File> fileList = iterator(file, filter);
        StringBuilder fileName = new StringBuilder();
        fileList.forEach(obj->{
            try {
                String targetFile = ncmService.ncm2NormalFormat(obj);
                fileName.append(";").append(targetFile);
            } catch (TagException | ReadOnlyFileException | CannotReadException | InvalidAudioFrameException | IOException | CannotWriteException e) {
                e.printStackTrace();
            }
        });
        return fileName.toString().replaceFirst(";","");
    }

    /**
     * 过滤目录中的ncm文件
     * @param rootFile
     * @param filter
     * @return
     */
    private List<File> iterator(File rootFile, final FileFilter filter)
    {
        List<File> fileList = new ArrayList<>();
        if (!rootFile.isDirectory()){
            fileList.add(rootFile);
            return fileList;
        }
        File[] files = rootFile.listFiles(pathname -> pathname.isDirectory() || filter.accept(pathname));
        if (files != null && files.length > 0){
            Collections.addAll(fileList, files);
        }
        return fileList;
    }
}
